package handler

import (
	"net/http"

	"octopus/internal/domain/entities"
	"octopus/internal/usecase/container_usecase"

	"github.com/gin-gonic/gin"
)

type ContainerHandler struct {
	service *container_usecase.ContainerService
}

func NewContainerHandler(service *container_usecase.ContainerService) *ContainerHandler {
	return &ContainerHandler{
		service: service,
	}
}

func (h *ContainerHandler) ListContainers(c *gin.Context) {
	containers, err := h.service.ListContainers()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, containers)
}

// // broadcast 是一个全局的 WebSocket 广播函数，需要在实际项目中实现
// var broadcast func(msg interface{})

func (h *ContainerHandler) StopContainer(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Container ID is required"})
		return
	}

	// 启动异步任务
	taskID := h.service.AsyncStopContainer(id, func(task *entities.Task) {
		if broadcast != nil {
			broadcast(gin.H{
				"event": "container:stop:done",
				"task":  task,
			})
		}
	})

	c.JSON(http.StatusAccepted, gin.H{
		"message": "Container stop task submitted",
		"taskID":  taskID,
	})
}

func (h *ContainerHandler) RestartContainer(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Container ID is required"})
		return
	}

	// 启动异步任务
	taskID := h.service.AsyncRestartContainer(id, func(task *entities.Task) {
		if broadcast != nil {
			broadcast(gin.H{
				"event": "container:restart:done",
				"task":  task,
			})
		}
	})

	c.JSON(http.StatusAccepted, gin.H{
		"message": "Container restart task submitted",
		"taskID":  taskID,
	})
}
